<template>
  <!--  预警级别列表页面-->
  <div class="page">
    <div class="detail-header" v-if="isControl">
      {{projectDetail.name}}
    </div>
    <!-- 消息管理 -->
    <div class="page_filter">
      <el-cascader v-if="!isProject" :props="propsCascader" ref="refHandle" filterable clearable v-model="selectedOptions"
                   change-on-select
                   placeholder="请选择项目/监测对象/监测点" style="width: 50%" @change="form.page=1;queryList()"></el-cascader>
      <el-input placeholder="请输入预警值" v-model="contrastValue" class="input-with-select" clearable
                style="width: 350px;margin-left: 20px">
        <el-select v-model="contrastType" slot="prepend" placeholder="请选择" style="width: 110px">
          <el-option label="大于等于" value="minValue"></el-option>
          <el-option label="小于等于" value="maxValue"></el-option>
        </el-select>
        <template slot="append">
          <el-button size="mini" icon="el-icon-search" @click="form.page=1;queryList()">过滤</el-button>
        </template>
      </el-input>

    </div>
    <div class="common_btnBox">
      <i class="iconfont iconzongshu icon-size"></i>
      总数：{{form.total}}
    </div>
    <div class="page_main">
      <div style="padding-bottom: 10px">
        <el-radio-group v-model="form.cleanFlag" @change="form.page=1;queryList()" style="margin-right: 20px">
          <el-radio-button v-for="item in EnumReadFlagList" :label="item.code" :key="item.code">{{item.name}}
          </el-radio-button>
        </el-radio-group>

        <el-radio-group v-model="form.warningLevel" @change="form.page=1;queryList()">
          <el-radio-button label=""><i class="el-icon-s-operation radio-button_icon"></i>所有等级
          </el-radio-button>
          <el-radio-button v-for="item in EnumWarningLevelList" v-show="item.code>1" :label="item.code"
                           :key="item.code">{{item.name}}
          </el-radio-button>
        </el-radio-group>

        <el-radio-group v-model="form.monitorType" @change="form.page=1;queryList()" style="margin-top: 20px">
          <el-radio-button label=""><i class="iconfont icongongyinglianziliao radio-button_icon"></i>所有类型
          </el-radio-button>
          <el-radio-button v-for="item in EnumProjectMonitorTypeList" :key="item.code" :label="item.code">
            <i class="iconfont radio-button_icon" :class="item.code | gradeMonitorType"></i>{{item.name}}
          </el-radio-button>
        </el-radio-group>
        <!-- 条件筛选 -->
        <div style="margin-top: 10px">
          <el-popconfirm title="确定消除监测点当前预警吗？若设备未恢复正常，下次依然产生预警！" @confirm="deleteInfo" class="popconfirmBox"
                         style="background: red">
            <el-button type="primary" icon="el-icon-thumb" slot="reference">消除预警</el-button>
          </el-popconfirm>
          <el-button type="success" icon="el-icon-s-promotion" style="margin-left: 20px" @click="pushMessage">短信推送
          </el-button>
        </div>
      </div>
      <!-- table -->
      <el-table :data="tableList" border @selection-change="handleSelectionChange">
        <el-table-column label="序号" fixed width="80">
          <template slot-scope="scope">
            {{getIndex(scope.$index)}}
          </template>
        </el-table-column>
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="projectName" label="监测信息" min-width="320">
          <template slot-scope="scope">
            【{{scope.row.projectName}}】{{scope.row.workPointName}}，{{scope.row.monitorPointName}}
          </template>
        </el-table-column>
        <el-table-column prop="monitorTypeName" label="监测类型" width="120"></el-table-column>
        <el-table-column prop="recordValueName" label="预警数据" show-overflow-tooltip width="140"></el-table-column>
        <el-table-column prop="warningLevelName" label="预警等级" width="105">
          <template slot-scope="scope">
            <el-tag size="mini" :style="scope.row.warningLevel | gradeColor">{{scope.row.warningLevelName}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="预警时间" width="180">
          <template slot-scope="scope">
            {{scope.row.createTime|formatTimer()}}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="130">
          <template slot-scope="scope">
            <button class="btn_add" @click="toMonitor(scope.row)">查看曲线</button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="form.page"
                     :page-size="form.pageSize" :page-sizes="[10, 20, 30, 40,50,60,70,80,90,100]"
                     layout="sizes, prev, pager, next" :total="form.total">
      </el-pagination>
    </div>

    <!-- 新增编辑弹窗 -->
    <el-drawer title="推送列表" :visible.sync="isShowPush" :close-on-click-modal="false" size="75%">
      <!-- 具体form表单 -->

      <div class="demo-drawer__content">
        <div style="padding: 0px 10px" class="sms_view">
          <el-table :data="userListProject" highlight-row style="margin-bottom: 20px;" height="80vh" border
                    @selection-change="handleSelectionChangePush">
            <el-table-column label="序号" fixed width="70" align="center" disabled>
              <template slot-scope="scope">
                {{scope.$index + 1}}
              </template>
            </el-table-column>
            <el-table-column type="selection" width="40" align="center">
              <template slot-scope="{ row }">
                <el-checkbox v-model="pushSelectionList" :label="row"></el-checkbox>
              </template>
            </el-table-column>

            <el-table-column prop="userType" label="用户类型" width="250">
              <template slot-scope="scope">
                <el-radio-group disabled v-model="scope.row.userType" size="mini">
                  <el-radio-button :label=4>监测单位</el-radio-button>
                  <el-radio-button :label=5>业主单位</el-radio-button>
                </el-radio-group>
              </template>
            </el-table-column>
            <el-table-column prop="pushType" label="推送方式" width="250">
              <template slot-scope="scope">
                <el-radio-group v-model="scope.row.type" size="mini" @change="changeType(scope.$index,scope.row.type)"
                                disabled>
                  <el-radio-button :label=1>短信</el-radio-button>
                  <el-radio-button :label=2>公众号</el-radio-button>
                  <el-radio-button :label=3>手动录入</el-radio-button>
                </el-radio-group>
              </template>
            </el-table-column>
            <el-table-column prop="userName" label="通知账号" min-width="200">
            </el-table-column>
            <el-table-column prop="phone" label="通知号码" min-width="200">
              <template slot-scope="scope">
                <el-input v-model="scope.row.phone" disabled show-word-limit maxlength="11"
                          clearable placeholder="手机号"
                          oninput="this.value = this.value.replace(/[^0-9]/g, '');"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" min-width="200">
              <template slot-scope="scope">
                <el-input disabled type="text" v-model="scope.row.remark" placeholder="备注"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="user" label="预警等级>=时发送通知" min-width="200">
              <template slot-scope="scope">
                <el-select v-model="scope.row.level" size="mini" clearable placeholder="选择预警等级" disabled>
                  <el-option
                    v-for="item in EnumWarningLevelList"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                    :disabled="item.code === 1">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <!-- 操作按钮 -->
      <div class="demo-drawer__footer">
        <el-button class="common_btn-white" @click="isShowPush = false">取消</el-button>
        <el-button class="common_btn-defalut" type="primary" @click="validateForm">确定</el-button>
      </div>
      <span class="demo-drawer__footer">

      </span>
    </el-drawer>
    <x-loading v-show="isLoading"></x-loading>
  </div>
</template>

<script>
  import {
    projectSelect, workSelect, monitorSelect,
  } from '@/services/model/project-info.js'
  import {
    recordWarningList, recordWarningPushList,
    pushMessage,
    monitorWarningClean
  } from '@/services/model/warning.js'
  import ItemMixins from "@/views/form/item.mixins";
  import Format from '@/utils/format'
  import XLoading from '@/components/animation/x-loading.vue'
  import Enums from '@/utils/enums'
  import {actions, store} from "./work-point.store";

  export default {
    components: {XLoading},
    mixins: [ItemMixins, Enums],
    data() {
      return {
        userListProject: [],
        warning: {
          warningFlag: 0
        },
        idList: [],
        monitorWarning: {},
        // 接口正在加载
        isLoading: false,
        form: {
          page: 1,
          pageSize: 10,
          total: 0,
          monitorType: '',
          warningLevel: '',
          cleanFlag: 0,
        },
        contrastType: 'minValue',//比较方式；maxValue小于等于contrastValue，minValue大于等于contrastValue
        contrastValue: '',//查询的值
        // 列表勾选的数据
        selectionList: [],
        pushSelectionList: [],
        pushProject: '',
        tableList: [],
        EnumReadFlagList: [
          {code: 0, name: '待处理'},
          {code: 1, name: '已处理'},
        ],
        EnumWarningLevelList: [],
        EnumProjectMonitorTypeList: [],
        isShowPush: false,
        currentRow: {
          phoneList: []
        },
        selectedOptions: [],
        propsCascader: {
          lazy: true,
          label: 'name',
          value: 'id',
          lazyLoad(node, resolve) {
            const {
              level,
              data
            } = node
            if (level === 0) {
              projectSelect().then(res => {
                const {
                  data
                } = res
                resolve(data)
              })
            } else if (level === 1) {
              workSelect({
                id: data.id
              }).then(res => {
                const {
                  data
                } = res
                resolve(data)
              })
            } else if (level === 2) {
              monitorSelect({
                id: data.id
              }).then(res => {
                const data = res.data.map(x => ({
                  ...x,
                  leaf: true
                }))
                resolve(data)
              })
            } else {
              resolve([])
            }
          }
        },
      }
    },
    computed: {
      isControl() {
        if (this.$route.params.projectId) {
          return true
        }
        return false
      },
      projectDetail() {
        return store.projectInfo
      },
      // true  监测单位展示
      isAuthority() {
        return this.$store.state.userInfo.unitType === 4
      },
      isProject() {
        return this.$route.params?.projectId
      },
    },
    filters: {
      // 时间格式化
      formatTimer(timer) {
        return Format(new Date(timer))
      },
      gradeMonitorType(val) {
        let iconMap = {
          1: 'iconshenbuweiyicexieyi',
          2: 'iconGNSS',
          3: 'iconlaxianweiyi',
          4: 'iconjiangyuliang',
          5: 'icondixiashuiwei',
          6: 'iconmaosuochuanganqi',
          7: 'iconjinglishuizhunyi2',
          8: 'iconqingjiao',
          9: 'iconxianxingtu',
          10: 'iconshidu',
          11: 'iconfengsufengxiangjiance',
          12: 'icondiyingli',
          13: 'iconzhendong',
          14: 'iconjianshiqicai01',
          15: 'iconGNSS',
          16: 'iconjianshiqicai01',
          17: 'iconzhendong',
          18: 'iconleida',
          19: 'iconshengguangbaojing',
          20: 'icona-fenzu1',
          21: 'iconzhendong',
          22: 'icondb_fill',
          23: 'iconzhendong',
        }
        return iconMap[val]
      },
      gradeColor(val) {
        switch (val) {
          case 2:
            return 'background-color:#0073b7;color:white'
          case 3:
            return 'background-color:#f39c12;color:white'
          case 4:
            return 'background-color:#ff851b;color:white'
          case 5:
            return 'background-color:#e43321;color:white'
          default:
            return 'background-color:#0DC26B;color:white'
        }
      },
    },
    methods: {
      handleAddPhone() {
        if (this.currentRow.phoneList.length >= 5) {
          this.$message.info('最多添加5位接收人！')
          return
        }
        this.currentRow.phoneList.push({})
      },
      // 删除电话
      handleDeletePhone(index) {
        this.currentRow.phoneList.splice(index, 1);
      },
      async validateForm() {
        let form = {
          id: this.pushProject,
          userList: this.pushSelectionList
        }
        let res = await pushMessage(form)
        if (res.code === 200) {
          this.$notify({
            type: 'success',
            title: '提示',
            message: '预警短信发送成功'
          })
        }
        this.isShowPush = false
      },
      pushMessage() {
        if (!this.selectionList.length) {
          this.$message.info('请先勾选需要发送预警的消息！')
          return
        }
        if (this.selectionList.length > 1) {
          this.$message.info('只能选择一条消息！')
          return
        }
        this.currentRow = {
          phoneList: []
        }
        //推送人员名单
        this.getPushList()
        this.currentRow.idList = this.selectionList.map(x => x.id)
        this.isShowPush = true
      },
      async getPushList() {
        this.pushSelectionList = []
        this.pushProject = this.selectionList[0].id
        let res = await recordWarningPushList(this.selectionList[0])
        res.data.map(x => {
          if (x.userType === 5) {
            this.pushSelectionList.push(x)
          }
        })
        this.userListProject = res.data
      },
      async handleCleanWarning() {
        let res = await monitorWarningClean({id: this.warning.monitorPointId})
        if (res.code === 200) {
          this.$notify({
            type: 'success',
            title: '提示',
            message: '预警消除成功'
          })
        }
      },
      // 获取当前的序号
      getIndex(index) {
        let param = (this.form.page - 1) * this.form.pageSize + index + 1
        return param
      },
      // 分页大小改变
      handleSizeChange(val) {
        this.form.pageSize = val
        this.queryList()
      },
      // 当前页码改变
      handleCurrentChange(val) {
        this.form.page = val
        this.queryList()
      },
      // 列表查询
      async queryList() {
        this.isLoading = true
        this.form.projectId = this.isProject ? this.isProject : ''
        this.form.workPointId = ''
        this.form.monitorPointId = ''
        if(!this.isProject){
          this.$refs.refHandle.dropDownVisible = false; //监听值发生变化就关闭它
        }
        // 级联选择器处理
        this.selectedOptions.forEach((item, index, arr) => {
          if (item) {
            if (index === 0) {
              this.form.projectId = item
            } else if (index === 1) {
              this.form.workPointId = item
            } else {
              this.form.monitorPointId = item
            }
          }
        })
        this.form.maxValue = ''
        this.form.minValue = ''
        this.form[this.contrastType] = this.contrastValue
        let res = await recordWarningList(this.form)
        this.tableList = res.data?.records
        this.form.page = Number(res.data?.current)
        this.form.total = Number(res.data?.total)
        this.isLoading = false
      },

      handleSelectionChange(val) {
        this.selectionList = val
      },
      handleSelectionChangePush(val) {
        this.pushSelectionList = val
      },
      // 备注
      handleEdit(val) {
        this.isShowDialog = true
        this.currentRow = JSON.parse(JSON.stringify(val))
      },
      // 修改消息
      async deleteInfo() {
        if (!this.selectionList.length) {
          this.$message.info('请先勾选需要清除预警的消息！')
          return
        }
        let idList = this.selectionList.map(x => x.monitorPointId)
        let res = await monitorWarningClean({idList: idList})
        if (res.code === 200) {
          this.$notify({
            type: 'success',
            title: '提示',
            message: '预警清除成功！'
          })
        }
        this.queryList()
      },
      // 去相应监测点
     async toMonitor(row) {
        if(!this.isControl){
          await actions.queryProjectInfo(row.projectId)
          await actions.queryWorkPointList(row.projectId)
        }
        this.$router.push({
          path: `/project/${row.projectId}/data-share?activeId=${row.monitorPointId}&monitorType=${row.monitorType}&workPointId=${row.workPointId}`
        })
      }
    },
    activated() {
      this.queryList()
    },
    mounted() {
      this.selectedOptions = [this.isProject]
      //	传感器型号下拉框
      this.queryDictList(['EnumWarningLevel', 'EnumProjectMonitorType'], ['EnumWarningLevelList', 'EnumProjectMonitorTypeList']);
    }
  }
</script>

<style scoped="scoped" lang="less">
  .page .page_filter
  /deep/ .el-input {
    width: 100%;
  }

  /deep/ .el-input-group__append {
    background-color: #2196f3;
    color: white;
    border: none;
  }

  /deep/ .el-radio-button__orig-radio:checked + .el-radio-button__inner {
    background: #1b1b1b;
  }

  .warning_info {
    span {
      color: #1990FE;
      margin-right: 10px;
      font-weight: 600;
    }

    padding: 10px;
    font-size: 15px;
  }


  .warning_label {
    margin-right: 10px;
    color: #1990FE;
    font-weight: 600;
  }

  .btn-other {
    color: #e6a23c;
  }

  /deep/ .el-table .read .cell {
    color: #C0C0C0 !important;
    // background-color: #ddd;
  }

  /deep/ .el-table .read {
    background-color: #fcfcfc;
  }

  .el-table {
    /deep/ .el-form-item__error {
      position: relative;
    }

  }

  .pushMessage {
    /deep/ .el-table {
      td, th {
        padding: 0px !important;
      }
    }
  }


</style>

